package com.zllkj.mm.module.home.fragments;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.bajian.sheetdialogue.SheetDialog;
import com.zllkj.mm.R;
import com.zllkj.mm.api.net.HttpManager;
import com.zllkj.mm.api.net.HttpOnNextListener;
import com.zllkj.mm.api.net.ProgressSubscriber_net;
import com.zllkj.mm.api.net.UploadPost;
import com.zllkj.mm.api.network.RetrofitHelper;
import com.zllkj.mm.api.network.RxHelper;
import com.zllkj.mm.api.network.subscriber.BaseString;
import com.zllkj.mm.api.network.subscriber.ProgressSubscriber;
import com.zllkj.mm.base.BaseTitleFragment;
import com.zllkj.mm.common.L;
import com.zllkj.mm.model.entity.GoodsClassifyAllListS2;
import com.zllkj.mm.util.ImageUtils;
import com.zllkj.mm.util.KLog;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;

import static android.app.Activity.RESULT_OK;


/**
 * 添加商品
 * Created by leon_ok.
 */

public class GoodsAddFragment extends BaseTitleFragment {

    @BindView(R.id.commodityNameEt)
    EditText commodityNameEt;
    @BindView(R.id.iv)
    ImageView iv;
    @BindView(R.id.priceEt)
    EditText priceEt;
    @BindView(R.id.instockEt)
    EditText instockEt;
    @BindView(R.id.CategoryTv)
    TextView CategoryTv;
    @BindView(R.id.deliveryTv)
    TextView deliveryTv;
    @BindView(R.id.confirmTv)
    TextView confirmTv;

    public static GoodsAddFragment newInstance() {
        return new GoodsAddFragment();
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_goodsadd;
    }

    @Override
    protected void initView(View rootView) {
        super.initView(rootView);
        setCommonTitle("添加商品");
    }

    @OnClick({R.id.iv,R.id.CategoryTv,R.id.deliveryTv, R.id.confirmTv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv:
                openImageChooserActivity();
                break;
            case R.id.CategoryTv:
                addSubscribe(RetrofitHelper.getInstance().getApi()
                        .goodsClassifyAllList2(L.sign(new HashMap()))
                        .compose(RxHelper.<GoodsClassifyAllListS2>defaultHandleResult())
                        .subscribe(new ProgressSubscriber<GoodsClassifyAllListS2>(getContext()) {
                            @Override
                            protected void onSucc(GoodsClassifyAllListS2 o) {

                            }
                        })
                );
                break;
            case R.id.deliveryTv:
                break;
            case R.id.confirmTv:
                addSubscribe(RetrofitHelper.getInstance().getApi()
                        .goodsAdd(L.sign(new HashMap() {{
                            put("deliveryMode", 1);//配送方式：1-包邮、2-送货上门、3-自提，此版本只做包邮
                            put("goodsClassifyId", 1);//商品分类ID
                            put("goodsName", commodityNameEt.getText().toString());
                            put("goodsPic", userLogo);//商品图，多张逗号隔开
                            put("stock", instockEt.getText().toString());//库存
                            put("unitPrice", priceEt.getText().toString());//单价
                        }}))
                        .compose(RxHelper.<BaseString>defaultHandleResult())
                        .subscribe(new ProgressSubscriber<BaseString>(getContext()) {
                            @Override
                            protected void onSucc(BaseString o) {
                                L.showToast("添加成功");
                                removeFragment();
                            }
                        })
                );
                break;
        }
    }


    String userLogo;
    SheetDialog sheetDialog;

    private void openImageChooserActivity() {
        sheetDialog = new SheetDialog(getActivity())
                .setTitle("请选择：")
                .setCanceledOnTouchOutside(false)
                .addSheetItems(new String[]{"相册", "拍照"}
                        , SheetDialog.SheetItemColor.Blue, which -> {
                            switch (which) {
                                case 1:
                                    getActivity().startActivityForResult(new Intent(Intent.ACTION_PICK).setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"), 102);
                                    break;
                                case 2:
                                    if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                                        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, 100);
                                        return;
                                    }
                                    path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + "zllImg.jpg";
                                    getActivity().startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(path))), 101);
                                    break;
                            }
                        }
                )
                .show()
        ;
    }

    String path;
    Disposable disposable;

    @Override
    public void onActivityResult(final int requestCode, int resultCode, final Intent data) {

        KLog.e("onActivityResult() called with: requestCode = [" + requestCode + "], resultCode = [" + resultCode + "], data = [" + data + "]");

        if (requestCode == 101 && resultCode == RESULT_OK) {
            if (data != null) { //当没有指定外部存储路径时为缩略图模式,意图中直接携带了缩略图
//                iv.setImageBitmap(((Bitmap) data.getExtras().get("data")));
            } else { //当指定路径,意图不再携带数据,用户自行读取文件并显示
//                iv.setImageBitmap(BitmapFactory.decodeFile(path));
            }
        }//RESULT_CANCELED

        if (resultCode == RESULT_OK && (requestCode == 101 || requestCode == 102)) {
//            if (data != null) {
//                iv.setImageBitmap(((Bitmap) data.getExtras().get("data")));
//            } else {
//                Bitmap bitmap = ImageUtils.getBitmap(fileUrl, 540, 960);
//                ImageUtils.writeBitmap(this, bitmap, dirPath, "yinhangka-1.png", Bitmap.CompressFormat.PNG);
//                iv.setImageBitmap(bitmap);
//            }

//            final File file = new File(requestCode == 101 ? path : ImageUtils.getImageAbsolutePath(getActivity(), data.getData()));

            disposable = Flowable.just(new ArrayList<String>() {{
                add(requestCode == 101 ? path : ImageUtils.getImageAbsolutePath((getActivity()), data.getData()));
            }})
                    .observeOn(Schedulers.io())
                    .map(new Function<List<String>, List<File>>() {
                        @Override
                        public List<File> apply(@NonNull List<String> list) throws Exception {
                            return Luban.with(getActivity()).load(list).setFocusAlpha(false).get();
//                            return new ArrayList<File>() {{
//                                add(file);
//                            }};
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<List<File>>() {
                        @Override
                        public void accept(List<File> files) {
                            KLog.e(files);
                            ProgressDialog progressDialog = new ProgressDialog(getContext());
                            progressDialog.show();
                            HttpManager.getInstance().doHttpDeal(new UploadPost(new ProgressSubscriber_net(new HttpOnNextListener<BaseString>() {
                                @Override
                                public void onNext(final BaseString baseString) {
                                    progressDialog.dismiss();
                                    userLogo = baseString.string;
                                    L.setImg(userLogo, iv);
                                }
                            }, getActivity(), true, false) {
                                @Override
                                public void onCancelProgress() {
                                    super.onCancelProgress();
                                    progressDialog.dismiss();
                                }
                            }, RequestBody.create(MediaType.parse("multipart/form-data"), /*file*/files.get(0))));
                        }
                    });


        }
//        if (resultCode == RESULT_OK && requestCode == 80) {
////            if (data != null) {
////                iv.setImageBitmap(((Bitmap) data.getExtras().get("data")));
////            } else {
////                Bitmap bitmap = ImageUtils.getBitmap(fileUrl, 540, 960);
////                ImageUtils.writeBitmap(this, bitmap, dirPath, "yinhangka-1.png", Bitmap.CompressFormat.PNG);
////                iv.setImageBitmap(bitmap);
////            }
//
//            HttpManager.getInstance().doHttpDeal(new UploadPost(new ProgressSubscriber(new HttpOnNextListener<BaseString>() {
//                @Override
//                public void onNext(final BaseString baseString) {
////                    try {
////                        new File(dirPath + "yinhangka-1.png").delete();
////                    } catch (Exception e) {
////                        e.printStackTrace();
////                    }
//
////                    r(new Runnable() {
////                        @Override
////                        public void run() {
////                            Cocos2dxJavascriptJavaBridge.evalString("cc.anysdkMgr.showAlbumCallback('" + baseString.string + "')");
////                        }
////                    });
//                    String a = baseString.string;
//                    String method = "javascript:payImageCallback(\"" + a + "\")";
//                    mWebView.loadUrl(method);
//                }
//            }, activity, true, false) {
//                @Override
//                public void onCancelProgress() {
//                    super.onCancelProgress();
//                }
//            }, RequestBody.create(MediaType.parse("multipart/form-data"), new File(ImageUtils.getImageAbsolutePath(this, data.getData())))));
//        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (null != sheetDialog) {
            sheetDialog.dismiss();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != disposable) {
            disposable.dispose();
        }
    }
}

